<?php

namespace app\controller\api;

use app\BaseController;
use app\model\StationBasic;
use app\model\StationPrice;
use app\model\Stations;
use think\helper\Str;
use think\response\Json;

class Order extends BaseController
{
    public function create(): Json
    {
        return $this->handle(function () {
            $param = $this->request->post();
            $station = $this->app->make(StationBasic::class)->where('id', $param['station_id'])->where('state', 1)->find();
            if (empty($station)) throw new \Exception('油站不存在');
            $oil = $this->app->make(StationPrice::class)->with(['oil'])->where('station_id', $param['station_id'])->where('oil_id', $param['oil_name'])->find();
            if (empty($oil)) throw new \Exception('油品不存在');
            $user = $this->request->user;
            $defMoney = $this->mathDiscount()->getData();
            if(empty($defMoney['result'])) throw new \Exception('金额计算异常！');
            $defMoney = $defMoney['result'];
            if (empty($user)) throw new \Exception('用户不存在');
            if ($user['balance'] < $defMoney['money']) throw new \Exception('余额不足');
            $number = $defMoney['litter'] ?? 0;
            $order = [
                "sid" => $user->supplier,
                "mid" => $station->opt_id,
                "gas_id" => $station->id,
                "order_sn" => date("YmdHis") . Str::random(4, 1),
                "payment_sn" => date("YmdHis") . Str::random(4, 1),
                "out_order_sn" => date("ymdHis") . Str::random(4, 1),
                "money" => $param['money'],
                "amount" => $defMoney['money'] ?? 0,
                "payment_money" => $defMoney['money'] ?? 0,
                "account" => $user['id'],
                "oil_type" => $oil['oil']['name'] ?? '',
                "gun" => $param['gun_no'] ?? '',
                "number" => $number,
                "state" => 7,
                "payment_time" => date("Y-m-d H:i:s")
            ];
            $model = new \app\model\Order;
            $model->startTrans();
            $model->save($order);
            $user->dec('balance', $defMoney['money'])->inc("freeze_balance", $defMoney['money'])->save();
            $model->commit();
            return $model->toArray();
        });
    }

    public function detail(): Json
    {
        return $this->handle(function () {
            $param = $this->request->get();
            $model = new \app\model\Order;
            $order = $model->with(['station'=>function ($query) {
                $query->with(['stationTip']);
            }])->where('order_sn', $param['order_sn'])->find();
            if (empty($order)) throw new \Exception('订单不存在');
            return $order->toArray();
        });
    }

    public function mathDiscount(): Json
    {
        //计算优惠价格
        return $this->handle(function () {
            $param = $this->request->param();
            $prices = $this->request->supplierPrice ?? [];
            $user = $this->request->user ?? [];
            $sup = $user['supplier'] ?? 0;
            $price = $prices[$param['oil'] ?? $param['oil_name']][$sup][$param['station'] ?? $param['station_id']] ?? $prices[$param['oil'] ?? $param['oil_name']][0][$param['station'] ?? $param['station_id']];
            $initMoney =  (float)$price['discount_price'];
            //计算加油数量
            $litter = $param['money']/$price['gun_price'];
            //计算实际支付金额
            $money = round($litter * $initMoney,2);
            $litter = round($litter, 2);
            //计算优惠金额
            $discount = (float)bcsub($param['money'], $money, 2);
            return compact('initMoney', 'litter', 'discount', 'money');
        });
    }
}
